import store from '@/store';

const whitePathList = ['/login', '/404'];

export function createPermissionGuard(router) {
  router.beforeEach(async(to, from, next) => {
    // 可以直接进入白名单页面
    if (whitePathList.includes(to.path)) {
      next();
      return;
    }
    // TODO
    // 未登录状态下跳转到 login 页

    // 判断是否已动态生成路由
    const { routes } = store.getters;
    if (!routes.length) {
      const routes = await store.dispatch('permission/generateRoutes');
      router.addRoutes(routes);
      next(to.fullPath);
      return;
    }
    else {
      if (to.matched.length === 0) {
        next({ path: '/404', replace: true });
        return;
      }
      next();
      return;
    }
  });
}
